package controller;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import model.Users;
import model.Wiadomosc;

public class Server implements Runnable{
	private int sPort;
    private ServerSocket serwer;
    private Socket gniazdo_klienta;
    private ObjectOutputStream wyjscie;
    private ObjectInputStream wejscie;
    private String host; 
    private Wiadomosc wiadomosc;
    
	@Override
	public void run() {
		int numer = 0;
		Socket s = null;
		ObjectOutputStream output;
		ObjectInputStream input;
		System.out.println("Serwer startuje na hoscie " + host);
		Users us = new Users();
		while (true) 
		{
			try 
			{
				s = serwer.accept();
				if (s == null) continue;
				output = new ObjectOutputStream(s.getOutputStream());
				output.flush();
				input = new ObjectInputStream(s.getInputStream());
				Client_Component komp_klienta =	new Client_Component(s,input,output,us);
				Thread watek_komponentu_klienta = new Thread(komp_klienta);
				watek_komponentu_klienta.start();
			} 
			catch (IOException e) 
			{System.out.println("Nie mozna polaczyc sie z klientem " + e);System.exit(1);} 
		}
	}
	
	public Server(int port_, String host_)
	{ 
		sPort = port_; host=host_;
	
		try
		{ 
			serwer = new ServerSocket(sPort);
		}
		catch(IOException e){System.out.println(e);}
	}
	
	public static void main(String args[]) throws Exception
	{
		String host_ = InetAddress.getLocalHost().getHostName();
		int Port = 5000;
		Server s = new Server(Port, host_);
		Thread t = new Thread(s);
		t.start();
	}
}
